package cn.com.cpic.insurance.rulecheck.core.element;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import cn.com.cpic.insurance.rulecheck.core.Context;
import cn.com.cpic.insurance.rulecheck.core.exception.OperateException;
import cn.com.cpic.insurance.rulecheck.core.function.CallFunction;

/**
 * 
 * 
 * @author 代波
 * @since 2011-8-15
 */
public final class CallElement implements Element<Comparable<?>> {
	private static final long serialVersionUID = 3599923359796658801L;

	private static final String FUNCTION_PREFIX = "cn.com.cpic.insurance.rulecheck.core.function.";
	private static final String FUNCTION_SUFFIX = "Function";

	private final CallFunction function;
	private final Element<Comparable<?>> elements[];

	public CallElement(String functionName, Element<Comparable<?>>... elements) {
		this.function = getFunctionInstance(functionName);
		this.elements = elements;
	}

	public Comparable<?> operate(Context context) throws OperateException {
		List<Comparable<?>> list = new ArrayList<Comparable<?>>();
		for (Element<Comparable<?>> element : elements) {
			list.add(element.operate(context));
		}

		return function.call(list.toArray(new Comparable<?>[list.size()]));
	}

	private static String getFunctionClassName(String functionName) {
		return FUNCTION_PREFIX + StringUtils.capitalize(functionName) + FUNCTION_SUFFIX;
	}

	private static CallFunction getFunctionInstance(String functionName) {
		String className = getFunctionClassName(functionName);
		Class<?> clazz;
		try {
			clazz = Class.forName(className);
		} catch (Exception e) {
			throw new IllegalArgumentException("加载类失败：" + className, e);
		}
		Object instance;
		try {
			instance = clazz.newInstance();
		} catch (Exception e) {
			throw new IllegalArgumentException("初始化类实例失败：" + clazz, e);
		}
		if (CallFunction.class.isInstance(instance)) {
			return (CallFunction) instance;
		} else {
			throw new IllegalArgumentException("类未实现[" + CallFunction.class + "]接口：" + clazz);
		}
	}
}
